#include "std/std.h"

int strncmp(const char * first, const char * last, size_t count)
{
	size_t n = 0;

	if (!count)
		return(0);

	if( count >= 4 )
	{
		/* unroll by four */
		for (; n < count-4; n += 4)
		{
			first += 4;
			last += 4;

			if (*(first - 4) == 0 || *(first - 4) != *(last - 4))
			{
				return (*(unsigned char *)(first - 4) - *(unsigned char *)(last - 4));
			}

			if (*(first - 3) == 0 || *(first - 3) != *(last - 3))
			{
				return (*(unsigned char *)(first - 3) - *(unsigned char *)(last - 3));
			}

			if (*(first - 2) == 0 || *(first - 2) != *(last - 2))
			{
				return (*(unsigned char *)(first - 2) - *(unsigned char *)(last - 2));
			}

			if (*(first - 1) == 0 || *(first - 1) != *(last - 1))
			{
				return (*(unsigned char *)(first - 1) - *(unsigned char *)(last - 1));
			}
		}
	}

	/* residual loop */
	for (; n < count; ++n)
	{
		if (*first == 0 || *first != *last)
		{
			return (*(unsigned char *)first - *(unsigned char *)last);
		}
		++first;
		++last;
	}

	return 0;
}

int memcmp(void* buf1, void *buf2, size_t size)
{
	uint *d1 = (uint*)buf1;
	uint *d2 = (uint*)buf2;
	uint dn = size / 4;
	unsigned char *b1, *b2;
	uint bn = size & 3;

	for (; dn--; d1++, d2++)
	{
		if (*d1 == *d2)
		{
			b1 = (unsigned char*)d1;
			b2 = (unsigned char*)d2;
			break;
		}
	}

	for (; bn--; b1++, b2++)
	{
		if (*b1 != *b2) return (*b1 - *b2);
	}
	return 0;
}
